package menu.lt.pers.menu.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import menu.lt.pers.menu.Bean.NODATA;
import menu.lt.pers.menu.Bean.ResultByClassIdBean;
import menu.lt.pers.menu.Bean.UserBean;
import menu.lt.pers.menu.R;
import menu.lt.pers.menu.RecipeInfo;
import menu.lt.pers.menu.dao.ResourceDao;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class RecipeByTimeRecyclerViewAdapter extends RecyclerView.Adapter<RecipeByTimeRecyclerViewAdapter.MyHolder> {
    private Context context;
    private List<ResultByClassIdBean.ResultBean.ListBean> list;
    private HashMap<String, Bitmap> bitmapList;
    private int totalRecipe;
    private int num;
    private int classid;
    private UserBean user;

    public RecipeByTimeRecyclerViewAdapter(Context context, int classid, UserBean user) {
        this.context = context;
        this.classid = classid;
        this.bitmapList = new HashMap<>();
        this.list = new ArrayList<ResultByClassIdBean.ResultBean.ListBean>();
        this.user = user;
        totalRecipe = 0;
        num = 50;
        new GetData().execute(classid,totalRecipe,num);
    }

    public Context getContext() {
        return context;
    }
    public void addList(){
        new GetData().execute(classid,totalRecipe,num);
        Log.i("RecipeByTimeRecyclerViewAdapter.addlist", "addList: "+"执行了查数据");
    }
    public List<ResultByClassIdBean.ResultBean.ListBean> getList() {
        return list;
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater
                .from(viewGroup.getContext())
                .inflate(R.layout.fragment_index_resource, viewGroup, false);
        MyHolder holder = new MyHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder myHolder, final int i) {
        if (bitmapList.get(list.get(i).getName()) != null) {
            myHolder.imageView1.setImageBitmap(bitmapList.get(list.get(i).getName()));
        } else {
            myHolder.imageView1.setImageResource(R.drawable.timg);
        }
        myHolder.tv1.setText(list.get(i).getName());
        myHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, RecipeInfo.class);
                Gson gson = new Gson();
                intent.putExtra("recipe",gson.toJson(list.get(i)));
                intent.putExtra("user",gson.toJson(user));
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class MyHolder extends RecyclerView.ViewHolder {
        private ImageView imageView1;
        private TextView tv1;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            imageView1 = itemView.findViewById(R.id.imageView1);
            tv1 = itemView.findViewById(R.id.tv_1);
        }
    }

    class GetBimap extends AsyncTask {
        private String key;

        @Override
        protected Bitmap doInBackground(Object[] params) {
            key = (String) params[1];
            if (bitmapList.get(key) == null) {
                String uripath = (String) params[0];
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(5000, TimeUnit.SECONDS)
                        .readTimeout(5000, TimeUnit.SECONDS)
                        .build();
                Request request = new Request.Builder()
                        .url(uripath)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        InputStream inputStream = response.body().byteStream();//得到图片的流
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        return bitmap;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o != null) {
                Bitmap bitmap = (Bitmap) o;
                bitmapList.put(key, bitmap);
                notifyDataSetChanged();
            }
        }
    }

    class GetData extends AsyncTask{

        @Override
        protected ResultByClassIdBean doInBackground(Object[] params) {
//            https://api.jisuapi.com/recipe/byclass?classid=2&start=0&num=10&appkey=yourappkey
            String uripath = ResourceDao.findRecipeClassUrl+
                    "classid="+params[0]+"&"+
                    "start="+params[1]+"&"+
                    "num="+params[2]+"&"+
                    "appkey="+ResourceDao.appkey;
            Log.i("RecipeByTimeRecyclerViewAdapter.ResultByClassIdBean", "doInBackground: "+uripath);
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(5000, TimeUnit.SECONDS)
                    .readTimeout(5000,TimeUnit.SECONDS)
                    .build();
            Request request = new Request.Builder()
                    .url(uripath)
                    .build();
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()){
                    String result = response.body().string();
                    Gson gson = new Gson();
                    ResultByClassIdBean resultByClassIdBean;
                    try{
                        resultByClassIdBean = gson.fromJson(result,ResultByClassIdBean.class);
                        return resultByClassIdBean;
                    } catch (com.google.gson.JsonSyntaxException e){
                        NODATA error = gson.fromJson(result,NODATA.class);
                        resultByClassIdBean = new ResultByClassIdBean();
                        resultByClassIdBean.setStatus(Integer.valueOf(error.getStatus()));
                        resultByClassIdBean.setMsg(error.getMsg());
                        return resultByClassIdBean;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            ResultByClassIdBean resultByClassIdBean = (ResultByClassIdBean) o;
            if (resultByClassIdBean!=null){
                if (resultByClassIdBean.getStatus() == 0){
                    totalRecipe = resultByClassIdBean.getResult().getNum()+totalRecipe;
                    for (int i=0;i<resultByClassIdBean.getResult().getList().size();i++){
                        ResultByClassIdBean.ResultBean.ListBean listBean =
                                resultByClassIdBean.getResult().getList().get(i);
                        new GetBimap().execute(listBean.getPic(), listBean.getName());
                        list.add(listBean);
                    }
                    notifyDataSetChanged();
                } else if (resultByClassIdBean.getStatus() == 205){
                    Toast.makeText(context,"没有更多数据了~",Toast.LENGTH_SHORT).show();
                }

            }
        }
    }
}
